package model

import (
	"server/share/config"
	"time"

	"github.com/hwcer/cosgo/schema"
	"github.com/hwcer/cosmo/update"
	"github.com/hwcer/updater"
	"github.com/hwcer/updater/dataset"
	"github.com/hwcer/updater/operator"
	"github.com/hwcer/yyds"
)

func init() {
	Register(&Collect{})
}

// Collect 图鉴
type Collect struct {
	Model  `bson:"inline"`
	Lv     int32 `json:"lv" bson:"lv"`         //好感度
	Exp    int32 `json:"exp" bson:"exp"`       //好感度
	Val    int32 `bson:"val" json:"val"`       //累计获得数量
	Bag    int32 `json:"bag" bson:"bag"`       //背包,IType
	Reward int32 `bson:"reward" json:"reward"` //好感度奖励
	Update int64 `bson:"update" json:"update"`
	Create int64 `bson:"create" json:"create"` //解锁时间
}

func (this *Collect) AddExp(v int32) {
	this.Exp += v
	for {
		expConfig := config.Data.LikeExp[this.Lv+1]
		if expConfig == nil {
			break
		}
		if this.Exp >= expConfig.Exp {
			this.Lv++
			this.Exp -= expConfig.Exp
		} else {
			break
		}
	}
}

// ----------------- 作为MODEL方法--------------------
func (this *Collect) Schema() *schema.Schema {
	sch, _ := schema.Parse(this)
	return sch
}

func (this *Collect) Clone() any {
	r := *this
	return &r
}
func (r *Collect) IType(iid int32) int32 {
	it := yyds.Config.GetIType(iid)
	if it == config.ITypeUnit {
		it = config.ITypeCollectUnit
	} else if it == config.ITypeChip {
		it = config.ITypeCollectChip
	}
	return it
}

func (this *Collect) Upsert(u *updater.Updater, op *operator.Operator) bool {
	return true
}

func (this *Collect) Getter(u *updater.Updater, coll *dataset.Collection, keys []string) error {
	tx := db.Omit("uid", "update")
	if len(keys) > 0 {
		tx = tx.Where("_id IN ?", keys)
	}

	var rows []*Collect
	if tx = tx.Find(&rows); tx.Error != nil {
		return tx.Error
	}
	for _, v := range rows {
		coll.Receive(v.OID, v)
	}
	return nil
}
func (this *Collect) Setter(u *updater.Updater, bw dataset.BulkWrite) error {
	return bw.Submit()
}

func (this *Collect) BulkWrite(u *updater.Updater) dataset.BulkWrite {
	bw := NewBulkWrite(this)
	return bw
}
func (this *Collect) BulkWriteFilter(up update.Update) {
	if !up.Has(update.UpdateTypeSet, "update") {
		this.Update = time.Now().Unix()
		up.Set("update", this.Update)
	}
}
